import { login, logout, getInfo, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userinfo: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, username) => {
    state.name = username
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERINFO: (state, userinfo) => {
    state.userinfo = userinfo
  }
}

const actions = {
  //  用户登录
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo)
        .then((response) => {
          // console.log(response, 456456)
          const { data } = response
          commit('SET_TOKEN', data)
          setToken(data)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then(async(response) => {
          const { data } = response
          // 获取登录用户的基本信息  根据ID获取角色详情
          // console.log(data)
          const response2 = await getUserDetailById(data.userId)
          // console.log(response2.data)
          const { username, staffPhoto } = response2.data
          commit('SET_USERINFO', { ...response2.data, ...data })
          commit('SET_NAME', username)
          commit('SET_AVATAR', staffPhoto)
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 用户注销
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken() // 必须先移除令牌
      // resetRouter() //重置路由
      commit('RESET_STATE')
      resolve()
    })
  }

  // // remove token
  // resetToken({ commit }) {
  //   return new Promise((resolve) => {
  //     removeToken() // 必须先删除令牌
  //     commit('RESET_STATE')
  //     resolve()
  //   })
  // }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
